var type = RequestURLParam.getParam("type"),
    id = RequestURLParam.getParam("id"),
    userid,
    username,
    orgid,
    ognid,
    urlTxt = "/wf/entrust/add/entrust";
var $
    , form
    , layer
    , layedit
    , laydate;
$(document).ready(function () {

    if (type == "new") {
        var html = "<legend>添加工作委托</legend>";
        $("#title").empty();
        $("#title").append(html);
    } else {
        var html = "<legend>编辑工作委托</legend>";
        $("#title").empty();
        $("#title").append(html);

    }
    UserInfo.init();
    userid = UserInfo.userId;
    username = UserInfo.userName;
    orgid = UserInfo.postList[0].orgId;
    ognid = UserInfo.ognId;
    layui.use(['form', 'layedit', 'laydate'], function () {
        $ = layui.jquery
            , form = layui.form
            , layer = layui.layer
            , layedit = layui.layedit
            , laydate = layui.laydate;


        laydate.render({
            elem: '#beginTime',
            type: 'datetime'
        });
        laydate.render({
            elem: '#endTime',
            type: 'datetime'
        });

        loadMandatary();

        //监听提交
        saveData();
        if (type == "edit") {
            urlTxt = "/wf/entrust/update",
                init_data();
        } else {
            $("#consignorName").val(username);
            $("#consignor").val(userid);
            loadWf();
        }
    });
});

function init_data() {
    ActHttpRequest("/wf/entrust/" + id, {}, function (data) {
        if (data.OK == "OK") {
            form.val("myform", {
                "entrustId": data.wfEntrust.entrustId,
                "consignor": data.wfEntrust.consignor,
                "beginTime": data.wfEntrust.beginTime,
                "endTime": data.wfEntrust.endTime,
                "entrustRemake": data.wfEntrust.entrustRemake
            });
            loadConsignor(data.wfEntrust.consignor);
            loadMandatary(data.wfEntrust.mandatary);
            loadWf(data.wfEntrust.wfId);
            form.render();
        }
    });
}
//加载委托人
function loadConsignor(consignor) {
    ActHttpRequest("/sys-user/" + consignor, {}, function (d) {
        $("#consignorName").val(d.sysUser.userName);
        $("#consignor").val(d.sysUser.id);
    });
}

//加载被委托人
function loadMandatary(mandatary) {
    ActHttpRequest("/sys-user/getPostIdListAll/" + orgid, {}, function (d) {
        var $html = "<option value=''>被委托人</option>";
        if (d.data != null) {
            $.each(d.data, function (index, item) {
                if (item != null && item.id != userid) {
                    $html += "<option value='" + item.id + "'" + ((item.id == mandatary) ? 'selected' : '') + ">" + item.userName + "</option>";
                } else {
                    $html += "<option value='" + item.id + "'" +">" + item.userName + "</option>";;
                }
            });
            $("select[name='mandatary']").empty();
            $("select[name='mandatary']").append($html);

            //append后必须从新渲染
            form.render('select');
        }
    });
}

//加载委托流程
function loadWf(wfid) {
    var wfids = [];
    if (wfid == undefined || wfid == "undefined") {

    } else {
        wfids = wfid.split(',');
    }
    ActHttpRequest("/wf/activity/authority/getUserAll", {}, function (data) {
        if (data.OK == "OK") {
            if (wfids.length > 0) {
                for (var i = 0; i < data.List.length; i++) {
                    var v = wfid.indexOf(data.List[i].wfId);
                    if(v != -1){
                        var wf = "<input type=\"checkbox\" name=\"wfId\"  lay-skin=\"primary\" value='" + data.List[i].wfId + "' title='" + data.List[i].wfName + "' checked >";
                        $("#checkWfId").append(wf);
                    }else{
                        var wf = "<input type=\"checkbox\" name=\"wfId\"  lay-skin=\"primary\" value='" + data.List[i].wfId + "' title='" + data.List[i].wfName + "' >";
                        $("#checkWfId").append(wf);
                    }
                }
            } else {
                for (var i = 0; i < data.List.length; i++) {
                    var wf = "<input type=\"checkbox\" name=\"wfId\"  lay-skin=\"primary\" value='" + data.List[i].wfId + "' title='" + data.List[i].wfName + "' >";
                    $("#checkWfId").append(wf);
                }
            }
            form.render('checkbox');
        }

    })
}

function saveData() {
    form.on('submit(submit)', function (data) {
        var formData = data.field;
        if (formData["wfId"] == undefined || formData["wfId"] == 'undefined') {
            layer.msg("委托流程不能为空！", {
                icon: 1,
                time: 2000 //2秒关闭（如果不配置，默认是3秒）
            });
            return false;
        }
        var v = "";
        $('input[type=checkbox]:checked').each(function () {
            v += ($(this).attr('value').trim() + ",");
        });
        v = v.substring(0, v.length - 1);
        formData["wfId"] = v;

        ActHttpRequest(urlTxt, formData, function (data) {
            if (type == "new") {
                if (data.OK == "OK") {
                    layer.msg('提交成功！', {
                        icon: 1,
                        time: 2000 //2秒关闭（如果不配置，默认是3秒）
                    }, function () {
                        var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
                        parent.layer.close(index);
                    })
                } else {
                    layer.msg("提交失败！流程中委托人或者被委托人存在未结束的委托记录！", {
                        icon: 1,
                        time: 2000 //2秒关闭（如果不配置，默认是3秒）
                    })
                }
            }
            else{
                if (data) {
                    layer.msg('修改成功！', {
                        icon: 1,
                        time: 2000 //2秒关闭（如果不配置，默认是3秒）
                    }, function () {
                        var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
                        parent.layer.close(index);
                    })
                } else {
                    layer.msg("修改失败！", {
                        icon: 1,
                        time: 2000 //2秒关闭（如果不配置，默认是3秒）
                    })
                }
            }
        });
        return false;
    });
}
